<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\RowActions\DeleteUserAction;
use App\Admin\Actions\Grid\Tools\UserListImportAction;
use App\Admin\Actions\Show\Refresh;
use App\Admin\Repositories\User;
use App\Models\User as AppUser;
use App\Models\Company;
use App\Support\Data;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\Tools;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class UserController extends AdminController
{
    protected function title()
    {
        return '医生';
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(), function (Grid $grid) {

            // $grid->disablePerPages();
            // $grid->paginate(10);

            $grid->model()->with(['adminUser']);
            if (!Admin::user()->can('batch-delete-user')) {
                $grid->disableRowSelector();
                $grid->disableBatchDelete();
            }



            $grid->scrollbarX();
            $grid->withBorder();

            $grid->addTableClass(['table-text-center']);
            $grid->column('id')->sortable();

            // $grid->column('username');
            $grid->column('realname', '姓名');
            $grid->column('phone', '手机号码');
            $grid->column('unit');
            $grid->column('unit_level')->using(User::getUnitLevelOptions())->label();
            $grid->column('department');
            $grid->column('title')->using(User::getUserTitleOptions())->label();
            $grid->column('created_at', '创建时间');
            $grid->column('adminUser.name', '代理人');
            $grid->column('adminUser.region', '区域')->display(function ($id) {
                $region = Data::getRegion();
                return isset($region[$id]) ? $region[$id] : '-';
            });
            $grid->column('company_id', '公司')->display(function ($company_id) {
                return Company::find($company_id)->company_name ?? '';
            });




            $grid->model()->orderBy('id', 'desc');
            /**
             * 工具按钮.
             */
            $grid->tools(function (Tools $tools) {

                if (Admin::user()->can('user-list-import')) {
                    $tools->append(new UserListImportAction());
                }
            });
            // $grid->actions(function (Grid\Displayers\Actions $actions) {
            //     // 专家协议
            //     $actions->prepend('<a href="/agreement?project_id=' . 9 . '&uid=' . $actions->row->id . '" class="text-custom" style="margin-right: 10px;"><i class="fa fa-list"></i>专家协议</a>');
            // });
            /**
             * 按钮控制.
             */
            // @permissions
            if (!Admin::user()->can('user-create')) {
                $grid->disableCreateButton();
                // $grid->disableQuickCreateButton();
            }

            // @permissions
            if ((!Admin::user()->can('user-update'))) {
                $grid->disableEditButton();
                // $grid->disableQuickEditButton();
            }
            // @permissions
            // if (!Admin::user()->can('user-delete')) {
            $grid->disableDeleteButton();
            // }

            // @permissions
            if (!Admin::user()->can('user-view')) {
                $grid->disableViewButton();
            }
            $grid->disableViewButton();
            $grid->actions(function (Grid\Displayers\Actions $actions) {

                // if ($this->status != -2) { // || Admin::user()->can('agreement-termination')
                //     if (Admin::user()->isAdministrator()) {
                $actions->append(new DeleteUserAction()); // 自定义删除
                // }
                // }



            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('realname', '专家姓名');
                $filter->like('phone', '手机号');
                $filter->like('unit');
                $filter->like('department');
                $filter->like('title')->select(User::getUserTitleOptions());
                $filter->like('unit_level')->select(User::getUnitLevelOptions());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->field('id');
            // $show->field('username');
            $show->field('realname', '姓名');

            // $show->field('province_id', '省')->as(function ($code) {

            //     return DcatDistpickerHelper::getAreaName($code);
            // });
            // $show->field('city_id', '市')->as(function ($code) {
            //     return DcatDistpickerHelper::getAreaName($code);
            // });
            // $show->field('district_id', '区')->as(function ($code) {

            //     return DcatDistpickerHelper::getAreaName($code);
            // });

            $show->field('00', '医院名称');

            $show->field('1', '职业');
            $show->field('2', '科室');
            $show->field('3', '医院级别');
            $show->image('医师资格证/工作证');

            $show->field('phone', '手机号码');
            $show->field('4', '银行卡号');
            $show->field('5', '开户名');
            $show->field('6', '开户银行');
            $show->field('7', '开户地');
            $show->field('8', '身分证号');
            $show->field('9', '收款人手机号码');

            $show->field('10', '单位')->as(function ($ins) {

                return implode(',', json_decode($ins, true));
            });
            $show->field('review_status', '审核状态');

            $show->field('updated_at', '审核时间');
            $show->field('created_at', '创建时间');

            $show->status()->using(['0' => '禁用', '1' => '启用']);





            $show->tools(function (Show\Tools $tools) {
                $tools->append(new Refresh());
            });
        });
    }

    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            $form->disableEditingCheck();
            $form->disableCreatingCheck();
            $form->disableViewCheck();
            $form->disableListButton();
            $form->disableViewButton();

            $form->tools(function (Form\Tools $tools) {
                $tools->append('<a href="javascript:history.back(-1)" class="btn btn-primary dialog-create">列表</a>');
            });


            // $projectID = request()->input('project_id');
            $admin = Admin::user();

            $form->hidden('company_id')->value($admin->company_id);
            $form->hidden('agent')->value($admin->id);
            $form->hidden('agent_code')->value($admin->employee_number);
            $form->hidden('status')->value(1);
            // $form->selectTable('realname', '姓名')->title('弹窗标题')
            //     ->dialogWidth('50%') // 弹窗宽度，默认 800px
            //     ->from(UserTable::make(['id' => $form->getKey()])) // 设置渲染类实例，并传递自定义参数
            //     ->model(User::class, 'id', 'realname') // 设置编辑数据显示
            //     ->required();
            $form->autocomplete('realname', '真实姓名')->options(AppUser::where('status', '1')->pluck('realname', 'id'))->required();
            // $form->button('填充数据')->addElementClass(['sendMessage']);


            $form->mobile('phone')->rules('required|regex:/^1[3-9]\d{9}$/', ['regex' => '手机号码格式不正确', 'required' => '请填写手机号码'])->required();
            $form->distpicker([
                'province_id' => '----省----',
                'city_id'     => '----市----',
                'district_id' => '----区----'
            ], '省市');
            $form->text('unit', '医院名称');
            $form->text('department', '科室');
            $form->select('unit_level', '医院级别')->options(User::getUnitLevelOptions())->addElementClass(['unit_level'], false);
            $form->select('title', '职称')->options(User::getUserTitleOptions());

            $form->text('id_number', '身份证号')->rules(['required', 'regex:/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/'], ['regex' => '身份证号码格式不正确', 'required' => '请填写身份证号码'])->required()->len(18);

            $form->text('bank_number', '银行卡号')->required();
            $form->text('bank_opening', '开户行')->required()->help('请填写银行全称');
            $form->text('bank_account_open_local', '开户地')->required()->help('请填写省市地区');


            $form->image('certificate1', '职业医师资格证/工作证')->saveFullUrl()->move('tuofu/user-auth/certificate1/' . date('Y/m'))->autoUpload()->saving(function ($path) {
                return httpToHttps($path);
            });
            $form->image('certificate2', '职业医师资格证/工作证')->saveFullUrl()->move('tuofu/user-auth/certificate2/' . date('Y/m'))->autoUpload()->saving(function ($path) {
                return httpToHttps($path);
            });

            // $form->saving(function (Form $form) {
            //     $form->
            // });



            Admin::script(
                <<<JS
                $('.sendMessage').on('click',function(){
                  var title = $('input[name="realname"]').val();
                 var unit_level = $('select[name="unit_level"]');

                     $.ajax({
                                url: "/getUserInfo?userId="+title,
                                // data: 'userId='.title,
                                type: 'get',
                                contentType: 'json',
                                success: function (s) {
                                    console.log(s);
                                    if (s.code == 200) {

                                        $('input[name="phone"]').val(s.data.phone)
                                        $('input[name="unit"]').val(s.data.unit)
                                        $('input[name="department"]').val(s.data.department)

                                        $('select[name="province_id"]').val(s.data.province_id)
                                        $('select[name="city_id"]').val(s.data.city_id)
                                        $('select[name="district_id"]').val(s.data.district_id)

                                        $('select[name="unit_level"]').val(s.data.unit_level)
                                        // unit_level.find("option[value='"+s.data.unit_level+"']").attr('selected','selected')
                                        $('select[name="title"]').val(s.data.title)
                                        $('input[name="id_number"]').val(s.data.id_number)
                                        $('input[name="certificate1"]').val(s.data.certificate1)
                                        $('input[name="certificate2"]').val(s.data.certificate2)
                                    }
                                },
                                error: function(e) {
                                    console.error(e.message);

                                }
                            });
                });

                JS
            );
        });
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form_bak()
    {
        return Form::make(new User('auth'), function (Form $form) {
            // $form->display('id');

            $form->tab('认证信息', function (Form $form) {
                $form->text('auth.real_name', '姓名')->required();;
                $form->distpicker([
                    'province_id' => '----省----',
                    'city_id'     => '----市----',
                    'district_id' => '----区----'
                ], '省市');
                $form->text('auth.unit', '医院名称')->required();;
                $form->text('auth.carer', '职业')->required();;
                $form->text('auth.department', '科室')->required();;
                $form->text('auth.title', '职称')->required();;
                $form->text('auth.unit_level', '医院级别')->required();;
                $form->image('auth.certificate1', '医师资格证')->move('tuofu/user-auth/certificate1/' . date('Y/m'))->autoUpload()->required();;
                $form->image('auth.certificate2', '医师资格证')->move('tuofu/user-auth/certificate2/' . date('Y/m'))->autoUpload()->required();;
            })->tab('个人信息', function (Form $form) {
                $form->mobile('phone')->required();
                $id = $form->getKey();
                if ($id) {
                    $form->password('password', trans('admin.password'))
                        ->minLength(5)
                        ->maxLength(20)
                        ->customFormat(function () {
                            return '';
                        });
                } else {
                    $form->password('password', trans('admin.password'))
                        ->required()
                        ->minLength(5)
                        ->maxLength(20);
                }
                $form->text('bank_number', '银行卡号')->required();
                $form->text('bank_account_name', '开户名')->required();
                $form->text('bank_opening', '开户银行')->required();
                $form->text('bank_account_open_local', '开户地')->required();
                $form->text('id_number', '身份证号')->required();
                $form->text('payee_phone', '收款人手机号码')->required();
                $form->text('unit', '单位')->required();
            })->tab('审核', function (Form $form) {
                $form->radio('status')->options(['0' => '禁用', '1' => '启用'])->default('1');

                $form->radio('auth.review_status', '审核状态')->options(['0' => '未审核', '1' => '审核通过', '2' => '审核驳回'])->when(
                    [1, 2],
                    function (Form $form) {
                        // 值为1和4时显示文本框
                        $form->textarea('auth.reason', '审核意见');
                        $form->hidden('auth.examine_time')->value(Carbon::now());
                    }
                )->default('1');
            });
            $form->hidden('status')
                ->saving(function ($v) {
                    return $v;
                });
        })->saving(function (Form $form) {
            if ($form->password && $form->model()->get('password') != $form->password) {
                $form->password = bcrypt($form->password);
            }

            if (!$form->password) {
                $form->deleteInput('password');
            }
        });
    }



    public function getUserInfo(Request $request)
    {
        if (empty($request->input('userId'))) {
            return success();
        }
        // dd(AppUser::find($request->input('userId')));
        return success(AppUser::where('realname', 'like', '%' . $request->input('userId') . '%')->first());
    }
}
